//
//  SNSetViewController.m
//  ZhuoxinAgriculture
//
//  Created by stone on 16/12/10.
//  Copyright © 2016年 stone. All rights reserved.
//
#import "SDImageCache.h"
#import "ZXLoginViewController.h"
#import "HMNavigationController.h"
#import "Masonry.h"
#import "ZXForgetController.h"
#import "SNSetTextCell.h"
#import "SNSetViewController.h"
#import "SNSetNormalCell.h"
#import "AddModuleManager.h"

@interface SNSetViewController ()<UITableViewDataSource,UITableViewDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>
/** tableView */
@property (nonatomic,weak) UITableView * tableView;
/** titles */
@property (nonatomic,strong) NSArray<NSString *> * titles;
/** loginoutButton */
@property(weak, nonatomic) UIButton * loginoutButton;

@property(strong, nonatomic) UIImage * iconImage;


@end

@implementation SNSetViewController
/** titles 懒加载 */
- (NSArray<NSString *> *)titles {
    if (_titles == nil) {
        _titles = @[@"头像",@"修改密码",@"推送设置",@"清除缓存",@"关于卓信"];
    }
    return _titles;
}
//===================================== stone ===========/
- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = HexRGB(0xF5F5F5);
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"设置";
    
    CGRect frame = CGRectMake(12, 64+14, self.view.bounds.size.width-24, self.view.bounds.size.height - 64-14);
    UITableView * tableView = [[UITableView alloc] initWithFrame:frame style:UITableViewStyleGrouped];
    tableView.scrollEnabled = NO;
    self.tableView = tableView;
    [self setupInit:tableView];
    
    [self.view addSubview:tableView];
    

    UIButton * loginoutButton = ({
        UIButton * button = [[UIButton alloc] init];
        
        [button setTitle:@"退出登录" forState:UIControlStateNormal];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        
        button.titleLabel.font = [UIFont systemFontOfSize:15];
        
        [button setBackgroundImage:[SNUtils imageWithColor:HexRGB(0x67B245)] forState:UIControlStateNormal];
        // [button setImage:[UIImage imageNamed:@"selectedImage"] forState:UIControlStateSelected];
        
        [button addTarget:self action:@selector(loginoutButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
        
        button.layer.cornerRadius = 4;
        button.layer.masksToBounds = YES;
        // [self addSubview:button];
        // [self.contentView addSubview:button];
        [self.view addSubview:button];
        
        if (IS_IPHONE_4) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                CGRect rectInTableView = [self.tableView rectForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:5]];
                CGRect rect = [self.tableView convertRect:rectInTableView toView:self.view];
                CGFloat height = [UIScreen mainScreen].bounds.size.height - CGRectGetMaxY(rect);
                CGFloat bottomOffset = (height - 40) * 0.5;
                
                [button mas_makeConstraints:^(MASConstraintMaker * make) {
                    make.centerX.mas_equalTo(self.view.mas_centerX).offset(0);
                    make.bottom.mas_equalTo(self.view.mas_bottom).offset(-bottomOffset);
                    
                    make.width.mas_equalTo(140);
                    make.height.mas_equalTo(40);
                }];
            });
            
        }else{
            
            [button mas_makeConstraints:^(MASConstraintMaker * make) {
                make.centerX.mas_equalTo(self.view.mas_centerX).offset(0);
                make.bottom.mas_equalTo(self.view.mas_bottom).offset(-50);
                
                make.width.mas_equalTo(140);
                make.height.mas_equalTo(40);
            }];
        }

        button;
    });
    
    self.loginoutButton = loginoutButton;
    


    
    [self addObserver];
    [self addRequest];
}
-(void)loginoutButtonClicked:(UIButton *)sender {
    NSLog(@"%s", __func__);
    
    NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
    [defaults setObject:@"" forKey:@"token_key"];
    [defaults setObject:@"" forKey:@"passwordKey"];
    [defaults synchronize];
    
    [self presentViewController:[[HMNavigationController alloc]initWithRootViewController:[ZXLoginViewController new]] animated:YES completion:nil];
    
    [AddModuleManager sharedManager].homeAddModuleHomeconfigdomains = [NSMutableArray array];
}
#pragma mark - <addRequest>
- (void)addRequest {
    // addRequest
}
#pragma mark - <addObserver>
- (void)addObserver {
    // addObserver
}
- (void)dealloc {
    NSLog(@"%@ %s %@",[self class], __func__ , @"im dying");
}

- (void)setupInit:(UITableView *)tableView {
    tableView.delegate = self;
    tableView.dataSource = self;
    
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.backgroundColor = HexRGB(0xF5F5F5);
    [self setHeights:tableView];
    [self registerNib:tableView];
    [self registerClass:tableView];
}
#pragma mark - <Register>
/** registerNib */
- (void)registerNib:(UITableView *)tableView {
        [tableView registerNib:[UINib nibWithNibName:NSStringFromClass([SNSetNormalCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([SNSetNormalCell class])];
    [tableView registerNib:[UINib nibWithNibName:NSStringFromClass([SNSetTextCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([SNSetTextCell class])];
    
}
/** registerClass */
- (void)registerClass:(UITableView *)tableView {
    //    [tableView registerClass:[SNTableViewCell class] forCellReuseIdentifier:NSStringFromClass([SNTableViewCell class])];
    [tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:NSStringFromClass([UITableViewCell class])];
    //    [tableView registerClass:[UITableViewHeaderFooterView class] forHeaderFooterViewReuseIdentifier:NSStringFromClass([UITableViewHeaderFooterView class])];
}
#pragma mark - <SetHeights>
/** setHeights */
- (void)setHeights:(UITableView *)tableView {
    
    /** header */
    tableView.sectionHeaderHeight = 0.001;
    // tableView.estimatedSectionHeaderHeight = 100;
    // tableView.sectionHeaderHeight = UITableViewAutomaticDimension;
    /** cell */
//    tableView.estimatedRowHeight = 100;
//    tableView.rowHeight = UITableViewAutomaticDimension;
    tableView.rowHeight = 45;
    /** footer */
    tableView.sectionFooterHeight = 12;
    // tableView.estimatedSectionFooterHeight = 100;
    // tableView.sectionFooterHeight = UITableViewAutomaticDimension;
}

#pragma mark - <UITableViewDataSource>
/** 组数 */
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return self.titles.count;
}
/** 行数 */
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}
//MARK: -
//MARK: - cell
/** cell */

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell * cell;
    
    if (indexPath.section == 3) {
        cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([SNSetTextCell class])];
        cell.accessoryType = UITableViewCellAccessoryNone;
        
        SDImageCache * cache = [SDImageCache sharedImageCache];
        CGFloat size = [cache getSize];
        
        size = size / 1024.0;
        
        ((SNSetTextCell *)cell).cacheLabel.text =[NSString stringWithFormat:@"%.1fMB",size];
        
    }else{
        
        cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([SNSetNormalCell class])];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        if (indexPath.section == 0) {
            ((SNSetNormalCell *)cell).iconImageView.hidden = NO;
            if (self.iconImage == nil) {
                ((SNSetNormalCell *)cell).iconImageView.image = [UIImage imageNamed:@"default photo"];
            }else{
                ((SNSetNormalCell *)cell).iconImageView.image = self.iconImage;
            }
        }else{
            ((SNSetNormalCell *)cell).iconImageView.hidden = YES;
        }
    }
    
    cell.layer.shadowColor = HexRGB(0xdddddd).CGColor;//shadowColor阴影颜色
    cell.layer.shadowOffset = CGSizeMake(1,1);//shadowOffset阴影偏移,x向右偏移4，y向下偏移4，默认(0, -3),这个跟shadowRadius配合使用
    cell.layer.shadowOpacity = 1.0;//阴影透明度，默认0
    cell.layer.shadowRadius = 3;//阴影半径，默认3

    UILabel * label =  [cell valueForKey:@"titleLabel"];
    label.text = self.titles[indexPath.section];
    
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    
    return cell;
}
#pragma mark - <UITableViewDelegate>

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return 0.001;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    return 12;
}
/** 选中一行 */
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"%s", __func__);
//    _titles = @[@"头像",@"修改密码",@"推送设置",@"清除缓存",@"关于卓信"];
    switch (indexPath.section) {
        case 0://头像
        {

            WeakSelf(WSelf);
            
            UIAlertController * alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
            
            UIAlertAction * cancelAction =[UIAlertAction actionWithTitle:@"取消"
                                                                   style:(UIAlertActionStyleCancel)
                                                                 handler:^(UIAlertAction * _Nonnull action) {
                                                                     
                                                                 }];
            
            UIAlertAction * action1 =[UIAlertAction actionWithTitle:@"拍摄照片"
                                                              style:(UIAlertActionStyleDefault)
                                                            handler:^(UIAlertAction * _Nonnull action) {
                                                                [WSelf takePhoto];
                                                                
                                                            }];
            
            
            UIAlertAction * action2 =[UIAlertAction actionWithTitle:@"从手机相册选择"
                                                              style:(UIAlertActionStyleDefault)
                                                            handler:^(UIAlertAction * _Nonnull action) {
                                                                
                                                                [WSelf LocalPhoto];
                                                                
                                                            }];
            [alertController addAction:cancelAction];
            [alertController addAction:action1];
            [alertController addAction:action2];
            
            [self presentViewController:alertController animated:true completion:nil];
            
        }
            
            break;
        case 1://修改密码
        {
            ZXForgetController *vc = [[ZXForgetController alloc]init];
            vc.title = @"修改密码";
            [self.navigationController pushViewController:vc animated:YES];
            break;
        }
            
        case 2://推送设置
        {
            UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"ZXSetTableViewController" bundle:nil];
            UIViewController * vc = [storyboard instantiateViewControllerWithIdentifier:@"pushsetZX"];
            
            [self.navigationController pushViewController:vc animated:YES];
            
            break;
        }
            
        case 3://清除缓存
        {
            
            SDImageCache * cache = [SDImageCache sharedImageCache];
                
            [cache clearDisk];
            
            [self.tableView reloadData];
            
            
            
        }
            break;
        case 4://关于卓信
        {
            
            UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"ZXSetTableViewController" bundle:nil];
            UIViewController * vc = [storyboard instantiateViewControllerWithIdentifier:@"aboutZX"];
            
            [self.navigationController pushViewController:vc animated:YES];
            
            break;
        }
        case 5://检测更新
        {
            [self checkUpdate];
            break;
        }
            
        default:
            break;
    }
    
}
- (void)checkUpdate
{
    NSString * title = @"检测到新版本";
    NSString * message = @"是否下载更新?";
    NSString * actionButtonTitle1 = @"确定";
    NSString * actionButtonTitle2 = @"取消";
    
    UIAlertController * alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction * action1 = [UIAlertAction actionWithTitle:actionButtonTitle1 style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        // 确定之后需要 处理的code
        
    }];
    UIAlertAction * action2 = [UIAlertAction actionWithTitle:actionButtonTitle2 style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        // 取消之后需要 处理的code
        
    }];
    
    [alertController addAction:action1];
    [alertController addAction:action2];
    [self presentViewController:alertController animated:YES completion:nil];
}
/** 取消 选中 */
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath NS_AVAILABLE_IOS(3_0) {
    NSLog(@"%s", __func__);
}

// ------- 选择图片相关逻辑
#pragma mark -

//开始拍照
-(void)takePhoto
{
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])
    {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        //设置拍照后的图片可被编辑
        picker.allowsEditing = YES;
        picker.sourceType = sourceType;
        [self presentViewController:picker animated:YES completion:nil];
    }else
    {
        NSLog(@"模拟其中无法打开照相机,请在真机中使用");
    }
}

//打开本地相册
-(void)LocalPhoto
{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    //设置选择后的图片可被编辑
    picker.allowsEditing = YES;
    [self presentViewController:picker animated:YES completion:nil];
}

//当选择一张图片后进入这里
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info

{
    
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    
    //当选择的类型是图片
    if ([type isEqualToString:@"public.image"])
    {
        //先把图片转成NSData
        UIImage* image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        NSData *data;
        
        
        
        if (UIImagePNGRepresentation(image) == nil)
        {
            data = UIImageJPEGRepresentation(image, 1.0);
        }
        else
        {
            data = UIImagePNGRepresentation(image);
        }
        
        //图片保存的路径
        //这里将图片放在沙盒的documents文件夹中
        NSString * DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
        
        //文件管理器
        NSFileManager *fileManager = [NSFileManager defaultManager];
        
        //把刚刚图片转换的data对象拷贝至沙盒中 并保存为image.png
        [fileManager createDirectoryAtPath:DocumentsPath withIntermediateDirectories:YES attributes:nil error:nil];
        
        [fileManager createFileAtPath:[DocumentsPath stringByAppendingString:@"/image.png"] contents:data attributes:nil];
        
        //得到选择后沙盒中图片的完整路径
        //        NSString *filePath = [[NSString alloc]initWithFormat:@"%@%@",DocumentsPath,  @"/image.png"];
        
        //关闭相册界面
        [picker dismissViewControllerAnimated:YES completion:nil];
        
        //创建一个选择后图片的小图标放在下方
        //类似微薄选择图后的效果
        //        UIImageView *smallimage = [[UIImageView alloc] initWithFrame:self.userImageView.frame];
        //
        //        smallimage.image = image;
        //        //加在视图中
        //        [self.view addSubview:smallimage];
        
        
        self.iconImage = image;
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
    }
    
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    NSLog(@"您取消了选择图片");
    [picker dismissViewControllerAnimated:YES completion:nil];
}



@end
